import 'package:flutter/material.dart';
import 'package:flutter_danmu_anim/http/video.dart';
import 'package:flutter_danmu_anim/model/model_rec_video_item.dart';
import 'package:flutter_danmu_anim/model/model_response.dart';
import 'package:flutter_danmu_anim/utils/storage.dart';
import 'package:get/get.dart';
import 'package:hive/hive.dart';

class HomeController extends GetxController {
  final ScrollController scrollController = ScrollController();
  int count = 12;
  int _currentPage = 1;
  int crossAxisCount = 2;
  RxList<RecVideoItemModel> videoList = [RecVideoItemModel()].obs;
  bool isLoadingMore = false;
  bool flag = false;
  OverlayEntry? popupDialog;
  Box recVideo = GStorage.recVideo;

  @override
  void onInit() {
    super.onInit();
    if (recVideo.get('cacheList') != null &&
        recVideo.get('cacheList').isNotEmpty) {
      List<RecVideoItemModel> list = [];
      for (var i in recVideo.get('cacheList')) {
        list.add(i);
      }
      videoList.value = list;
    }
  }

  Future<ResponseListData<RecVideoItemModel>> queryRcmdFeed(type) async {
    var res = await VideoHttp.rcmdVideoList(
      ps: count,
      freshIdx: _currentPage,
    );
    if (res.status) {
      var list = res.data ?? [];
      if (type == 'init') {
        videoList.value = list;
      } else if (type == 'onRefresh') {
        videoList.insertAll(0, list);
      } else if (type == 'onLoad') {
        videoList.addAll(list);
        recVideo.put('cacheList', res.data);
      }
      _currentPage += 1;
      isLoadingMore = false;
    }
    return res;
  }

  // 下拉刷新
  Future onRefresh() async {
    queryRcmdFeed('onRefresh');
  }

  // 上拉加载
  Future onLoad() async {
    queryRcmdFeed('onLoad');
  }

  // 返回顶部并刷新
  void animateToTop() async {
    if (scrollController.offset >=
        MediaQuery.of(Get.context!).size.height * 5) {
      scrollController.jumpTo(0);
    } else {
      await scrollController.animateTo(0,
          duration: const Duration(milliseconds: 500), curve: Curves.easeInOut);
    }
  }
}
